<script setup>
import router from '@/router'
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getInfo } from '@/api/login'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

import { baseURL } from '@/utils/request.js'
import DefaultAvatar from '@/assets/images/profile.jpg'
const avatarUrl = ref(userStore.user.avatar ? baseURL + userStore.user.avatar : DefaultAvatar)

// 获取用户信息
function getUserInfo() {
  getInfo().then(res => {
    if (res.data.code === 200) {
      userStore.setUser(res.data.user)
      getReservation()
    } else {
      ElMessage.error('登录状态已过期，请重新登陆')
      router.push('/login')
    }
  })
}
getUserInfo()

// 违约情况
import { listReservation, updateReservation } from '@/api/reservation'
const DefaultStatus = ref(0) // 违约状态
const DefaultNumber = ref(0) // 违约次数
const StartTime = ref('')    // 禁约开始时间
const EndTime = ref('')      // 禁约结束时间
const remainingTime = ref('')// 禁约剩余时间
const BanTime = ref(7)       // 禁约时间/天 
const Remark = ref('')       // 备注
const cancelBtn = ref(false) // 禁约按钮

function getReservation() {
  listReservation({
    userId: userStore.user.userId,
    reservationStatus: '违约中',
  }).then(res => {
    DefaultNumber.value = res.data.total
    if (res.data.total >= 3) {
      DefaultStatus.value = '禁约'

      // 开始时间-结束时间
      const startDate = new Date(res.data.rows[0].reservationOutTime)
      const endDate = new Date(startDate)
      endDate.setDate(startDate.getDate() + BanTime.value)
      // 时间格式化函数
      const formatDateTime = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      StartTime.value = formatDateTime(startDate)
      EndTime.value = formatDateTime(endDate)
      updateRemainingTime()
      Remark.value = res.data.rows[0].remark
    } else {
      DefaultStatus.value = '正常'
    }
  })
}

let timer = null  // 定时器引用
// 计算并更新剩余时间
const updateRemainingTime = () => {
  if (EndTime.value) {
    const now = new Date()
    const end = new Date(EndTime.value)
    const diff = end.getTime() - now.getTime()
    if (diff > 0) {
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      remainingTime.value = `${days}天${hours}小时${minutes}分${seconds}秒`
    } else {
      remainingTime.value = '0天0小时0分0秒'
    }
    // 是否可以解除禁约
    if (DefaultStatus.value == '禁约') {
      cancelBtn.value = new Date() > new Date(EndTime.value)
    }
  }
}
// 启动定时器更新剩余时间
onMounted(() => { timer = setInterval(() => { updateRemainingTime() }, 1000) })
// 清理定时器
onUnmounted(() => { if (timer) { clearInterval(timer) } })
// 解除禁约
function cancelBan() {
  if (new Date() > new Date(EndTime.value)) {
    listReservation({
      userId: userStore.user.userId,
      reservationStatus: '违约中',
    }).then(res => {
      res.data.rows.forEach(item => {
        updateReservation({
          id: item.id,
          reservationStatus: '完成预约',
        }).then(res => {
          getReservation()
        })
      })
      cancelBtn.value = false
      ElMessage.success('预约状态已恢复正常')
    })
  }
}

// 我的预约
import MyReservation from '@/views/reservation/MyReservation.vue'
</script>

<template>
  <div class="index">
    <el-container>
      <el-header>自习室预约平台</el-header>
      <el-main>
        <!-- 我的信息 -->
        <div class="my-info">
          <div class="info">
            <el-avatar :size="50" :src="avatarUrl" />
            <div class="name">
              <p style="font-size: 18px;font-weight: bold;">你好，{{ userStore.user.nickName }}</p>
              <p style="font-size: 14px;">学号：{{ userStore.user.userName }}</p>
            </div>
          </div>
          <div class="status">
            <div class="box">
              <span v-if="DefaultNumber < 3">{{ DefaultNumber }}</span>
              <span v-else style="color: #F56C6C;">{{ DefaultNumber }}</span>
              <span>违约次数</span>
            </div>
            <div class="box">
              <span v-if="DefaultStatus == '正常'">{{ DefaultStatus }}</span>
              <span v-else style="color: #F56C6C;">{{ DefaultStatus }}</span>
              <span>预约状态</span>
            </div>
          </div>
          <el-alert v-if="DefaultStatus == '禁约'" type="error" :closable="false">
            <p><b>开始时间：</b>{{ StartTime }}</p>
            <p><b>结束时间：</b>{{ EndTime }}</p>
            <p><b>剩余时间：</b>{{ remainingTime }}</p>
            <p><b>违约原因：</b>{{ Remark }}</p>
          </el-alert>
          <el-button v-if="cancelBtn" type="warning" @click="cancelBan">解 除 禁 约</el-button>
        </div>
        <!-- 轮播图 -->
        <el-carousel>
          <el-carousel-item>
            <img src="@/assets/images/carousel/001.jpg">
          </el-carousel-item>
          <el-carousel-item>
            <img src="@/assets/images/carousel/002.jpg">
          </el-carousel-item>
          <el-carousel-item>
            <img src="@/assets/images/carousel/003.jpg">
          </el-carousel-item>
        </el-carousel>

        <!-- 我的预约 -->
        <MyReservation />
      </el-main>
    </el-container>
  </div>
</template>

<style lang="scss" scoped>
.index {
  height: 100%;

  .el-container {
    height: 100%;

    .el-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 40px;
      color: #555555;
      font-size: 16px;
      background-color: #ffffff;
    }

    .el-main {
      padding: 5px;

      .my-info {
        padding: 20px;
        color: #ffffff;
        background: linear-gradient(135deg, #409EFF, #36cfc9);
        border-radius: 10px;
        box-shadow: 0 4px 5px 0 #00000040;

        .info {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .status {
          display: flex;
          align-items: center;
          justify-content: space-around;
          margin-top: 10px;
          padding: 0 20px;
          font-size: 12px;

          .box {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;

            span:nth-child(1) {
              font-size: 20px;
              font-weight: bold;
            }
          }
        }

        .el-alert {
          margin-top: 10px;

          p {
            font-size: 12px;
          }
        }

        .el-button {
          margin-top: 10px;
          width: 100%;
        }
      }

      .el-carousel {
        margin: 10px 0;
        height: 160px;
        border-radius: 10px;
        box-shadow: 0 4px 5px 0 #00000040;

        img {
          width: 100%;
        }
      }
    }
  }
}
</style>